package com.cedarhd.finance.msg.domain.service;

import com.cedarhd.finance.msg.domain.entity.Point;
import com.cedarhd.finance.msg.domain.repository.PointRepository;
import com.cedarhd.finance.msg.dto.PointBackendDTO;
import com.cedarhd.finance.msg.dto.PointDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Evan
 * @date 2018/3/26
 */
@Service
public class PointService {

    @Autowired
    private PointRepository pointRepository;

    /**
     * 保存埋点
     * @param dto
     * @return
     */
    public Point save(PointDTO dto){
        if(StringUtils.isBlank(dto.getUserPhone())){
            dto.setUserPhone("UNKNOWN");
        }
        LocalDate today = LocalDate.now();
        Point point = pointRepository.findByUserPhoneAndPointTypeAndRecordDate(dto.getUserPhone(),dto.getPointType(),today.toString() );
        if(point != null){
            point.setNum(point.getNum()+1);
        }else {
            point = new Point();
            point.setNum(1);
            point.setUserPhone(dto.getUserPhone());
            point.setPointType(dto.getPointType());
            point.setDescription(dto.getPointType().getDescription());
            point.setRecordDate(today.toString());
        }

        return pointRepository.saveAndFlush(point);
    }

    public List<PointBackendDTO> coverDTO(Page<Point> pointPage){
        List<PointBackendDTO> result = new ArrayList<>();
        for(Point point: pointPage){
            PointBackendDTO dto = new PointBackendDTO();
            copyEntityToDTO(point,dto);
            result.add(dto);
        }
        return result;
    }

    private void copyEntityToDTO(Point point,PointBackendDTO dto){
        dto.setDescription(point.getDescription());
        dto.setPointType(point.getPointType());
        dto.setUserPhone(point.getUserPhone());
        dto.setId(point.getId());
        dto.setRecordDate(point.getRecordDate());
        dto.setNum(point.getNum());
        dto.setLastUpdated(point.getLastUpdated());
    }

    public PointRepository getRepository(){
        return this.pointRepository;
    }
}
